#!/usr/bin/env bash

# Copyright 2021 Flant CJSC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

source /shell_lib.sh

function __config__(){
  cat <<EOF
configVersion: v1
kubernetesValidating:
- name: prometheusremotewrite-policy.deckhouse.io
  group: main
  rules:
  - apiGroups:   ["deckhouse.io"]
    apiVersions: ["v1alpha1", "v1"]
    operations:  ["CREATE", "UPDATE"]
    resources:   ["prometheusremotewrites"]
    scope:       "Cluster"
kubernetes:
- name: prometheusremotewrites
  group: main
  executeHookOnEvent: []
  executeHookOnSynchronization: false
  keepFullObjectsInMemory: false
  apiVersion: deckhouse.io/v1
  kind: PrometheusRemoteWrite
  jqFilter: |
    {
      "name": .metadata.name,
      "url": .spec.url
    }
EOF
}

function __main__() {
  allowed=true
  message=""

  review_url="$(context::jq -r '.review.request.object.spec.url')"

  filtered_name=""
  if [[ "$(context::jq -r '.review.request.operation')" == "UPDATE" ]]; then
    filtered_name=$(context::jq -r '.review.request.name')
  fi

  if context::jq -e --arg url "$review_url" --arg filter "$filtered_name" '
    [
      .snapshots.prometheusremotewrites[].filterResult
      | select(.name != $filter)
      | .url
    ] | index($url)
  ' >/dev/null; then
    allowed=false
    message="Remote write URL '$review_url' is already in use"
  fi

  if [[ "$allowed" == "true" ]]; then
    cat <<EOF > $VALIDATING_RESPONSE_PATH
{"allowed":true}
EOF
  else
    cat <<EOF > $VALIDATING_RESPONSE_PATH
{"allowed":false, "message":"${message}"}
EOF
  fi
}

hook::run $@
